<template>
  <n-modal to="body" v-model:show="isShow" :mask-closable="false" transform-origin="center">
    <n-card class="avatar_set" :bordered="false" size="huge" role="dialog" aria-modal="true">
      <div class="main_setting">
        <h4 class="top_title">
          <span>{{ t("self_avatar") }}</span>
          <i>
            <iconpark-icon @click="isShow = false" icon-id="tanctongyguanb" color="#fff" size="1.2rem"></iconpark-icon>
          </i>
        </h4>
        <div class="main_body">
          <!-- 表格 -->
          <n-flex class="table_box">
            <n-flex justify="center" class="list_item" v-for="(item, index) in dataList" :key="index">
              <Imgt :class="curTab == item.value && 'active'" :src="`/img/head_icons/${item.value}.webp`"
                @click="clickTab(item)" />
            </n-flex>
            <n-flex @click="clickTab({ value: userAvatar })" justify="center" class="list_item"
              style="position: relative;" v-if="userAvatar">
              <img :class="curTab == userAvatar && 'active'" :src="settings.upload_url + '/' + userAvatar" alt="">
              <iconpark-icon @click.stop="curTab = userAvatar = ''" name="tanctongyguanb"
                style="position: absolute;right: -6px;top: -2px;border-radius: 50%;cursor: pointer;"></iconpark-icon>
            </n-flex>
            <n-flex v-else justify="center" class="list_item">
              <n-upload :max="1" @before-upload="beforeUpload" accept=".jpg,.jpeg,.png,.gif,.webp"
                :default-file-list="fileList" list-type="image-card">
                {{ t('click_upload') }}
              </n-upload>
            </n-flex>
          </n-flex>
          <!-- 底部 -->
          <n-flex align="center" justify="center" class="btn_bottom">
            <n-flex align="center" justify="center" class="button" @click="isShow = false">{{ t("home_page_cancel")
              }}</n-flex>
            <n-flex align="center" justify="center" class="button" @click="submitAction">{{ t("home_page_confirm")
              }}</n-flex>
          </n-flex>
        </div>
      </div>
    </n-card>
  </n-modal>
</template>

<script setup lang="ts">
import { computed, ref, watch, onMounted, onBeforeUnmount } from "vue";
import Imgt from "@/components/Imgt.vue";
import { useI18n } from "vue-i18n";
import { Message } from "@/utils/discreteApi";
import { storeToRefs } from "pinia";
import { User } from "@/store/user.ts";
import { Page } from '@/store/page.ts';
import pinia from "@/store";
import H5Websocket from "@/net/Net1";
import { MessageEvent2 } from '@/net/MessageEvent2';
import { NetMsgType } from '@/netBase/NetMsgType';
import { NetPacket } from "@/netBase/NetPacket";

const sta: any = ref(2) // 0-未设置 1-审核中 2-已通过 3-拒绝

const { t } = useI18n();
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
});
const emit = defineEmits(["update:visible", "avatarStatus"]);
const UserStore = User(pinia);
const PageStore = Page(pinia);
const { roleInfo } = storeToRefs(UserStore);
const { settings } = storeToRefs(PageStore);

const curTab: any = ref(roleInfo.value.head_photo);
const userAvatar: any = ref('')
watch(props, val => {
  if (val.visible) {
    curTab.value = roleInfo.value.head_photo
    if (roleInfo.value.head_photo.includes('.')) {
      userAvatar.value = roleInfo.value.head_photo
    }
  }
})
watch(roleInfo, () => {
  setTimeout(() => { // 获取审核状态
    getStatusAvatar()
  }, 1000)
})
const dataList: any = ref([
  // { value: '1001' },
  { value: '1002' },
  { value: '1003' },
  { value: '1004' },
  { value: '1005' },
  // { value: '1006' },
  // { value: '1007' },
  { value: '1008' },
  { value: '1009' },
  { value: '1010' },
  { value: '1011' },
  // { value: '1012' },
]);
const fileList = ref([]);

const isShow = computed({
  get: function () {
    return props.visible;
  },
  set: function (value) {
    emit("update:visible", value);
  },
});

const clickTab = (e: any) => {
  curTab.value = e.value;
};
const submitAction = () => {
  if (!curTab.value) return emit('update:visible', false)
  const query = NetPacket.req_select_head_icon()
  query.new_head_icon = curTab.value
  H5Websocket.sendMessageHandler(query);
};
// 获取头像审核状态
const getStatusAvatar = () => {
  const query = NetPacket.req_custom_head_icon_info()
  H5Websocket.sendMessageHandler(query);
}
const avatarStatusHandle = (res: any) => {
  sta.value = res.sta
  if (res.sta == 3) {
    Message.error(t('home_page_avatar_tip'));
  }
  if (res.sta == 0 || res.sta == 3) { // 设置为默认头像

  }
  emit('avatarStatus', res.sta)
}
// 上传图片
const beforeUpload = (data: any) => {
  const file = data.file.file;
  if (file && file.size > 1024 * 1024 * 2) {
    // 2MB限制
    Message.error("文件大小不能超过2MB！");
    return;
  }
  const formData = new FormData();
  formData.append("avatar", file);
  formData.append("role_id", `${roleInfo.value.id}`);
  fetch(`${settings.value.upload_url}/api/upload/avatar`, {
    method: "POST",
    body: formData,
  })
    .then((response) => response.json())
    .then((response) => {
      if (response.status == 200 || response.status == "success") {
        const urlImg = response.data.path;
        Message.success(response.message);
        curTab.value = urlImg
        userAvatar.value = urlImg
      } else {
        Message.error(response.message);
      }
    });
};



// 头像信息
const resultHandle = (rs: any) => {
  if (rs.is_success == 1) {
    emit('update:visible', false)
  } else {
    Message.error(t('home_page_avatar_error'));
  }
}

onMounted(() => {
  // 头像信息
  MessageEvent2.addMsgEvent(NetMsgType.msgType.msg_notify_select_head_icon_result, resultHandle);

  MessageEvent2.addMsgEvent(NetMsgType.msgType.msg_notify_custom_head_icon_info, avatarStatusHandle);
})

onBeforeUnmount(() => {
  MessageEvent2.removeMsgEvent(NetMsgType.msgType.msg_notify_select_head_icon_result, null);
  MessageEvent2.removeMsgEvent(NetMsgType.msgType.msg_notify_custom_head_icon_info, null);
})

</script>
<style lang="less" scoped>
@timestamp: `new Date() .getTime() `;

.avatar_set {
  :deep(.n-card__content) {
    padding: 0;
  }

  .main_setting {
    width: 852px;
    border-radius: 14px;
    border: solid 1.4px #322c59;
    overflow: hidden;

    .top_title {
      margin: 0;
      width: 100%;
      position: relative;
      height: 60px;
      line-height: 60px;
      font-size: 16px;
      color: #fff;
      border-top-left-radius: 14px;
      border-top-right-radius: 14px;
      text-align: center;
      border-bottom: 1px solid #26294c;
      background-color: #14173a;

      >i {
        position: absolute;
        top: 5px;
        right: 15px;
        cursor: pointer;
      }
    }

    .main_body {
      height: 560px;
      padding: 40px 40px;

      .table_box {
        gap: 30px !important;
        background: #0d0d29;
        border: 1px solid #4e4d6c54;
        border-radius: 20px;
        padding: 14px 22px;

        .list_item {
          width: 120px;
          height: 120px;

          img {
            cursor: pointer;
            width: 116px;
            height: 116px;
            border: 2px solid #231353;
            border-radius: 50%;

            &.active {
              border-color: #ad95f6;
            }
          }

          :deep(.n-upload) {
            display: flex;
            justify-content: center;
            align-items: center;
            background: #616161;
            border-radius: 10px;

            .n-upload-file-list {
              display: flex;
              width: 100%;
              height: 100%;

              .n-upload-trigger--image-card,
              .n-upload-file {
                width: 100%;
                height: 100%;

                .n-upload-dragger {
                  background: none;
                }
              }
            }
          }
        }
      }

      .btn_bottom {
        font-size: 18px;
        gap: 8px 34px !important;
        margin-top: 80px;

        >div {
          width: 178px;
          height: 54px;
          background: #212443;
          border-radius: 8px;

          &:last-child {
            background: linear-gradient(180deg, #5a6cff 0%, #7e1cff 100%);
            border-radius: 8px;
          }
        }
      }
    }
  }
}
</style>
